﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SendMailDemo
{
    public partial class SendMail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) return;
            SendMailFormModel model = new SendMailFormModel
            {
                SmtpServer=txtSmtpServer.Text.Trim(),
                SenderEmailAddress=txtSenderEmailAddress.Text.Trim(),
                SenderEmailPassword=txtSenderEmailPassword.Text.Trim(),
                Recipients=txtRecipients.Text.Trim(),
                Subject=txtSubject.Text.Trim(),
                Body=txtBody.Text.Trim()
            };

            try
            {
                //初始化Smtp服务器信息
                SmtpClient smtpClient = new SmtpClient(model.SmtpServer);
                //指定发件人信息  包括邮箱地址和邮箱密码
                smtpClient.Credentials = new NetworkCredential(model.SenderEmailAddress, model.SenderEmailPassword);

                MailMessage mail = new MailMessage();
                //初始化接收人信息
                string[] mailToArry = model.Recipients.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in mailToArry)
                {
                    mail.To.Add(item);
                }

                //发件人邮箱
                mail.From = new MailAddress(model.SenderEmailAddress, "这是显示名称");
                //邮件主题
                mail.Subject = model.Subject;
                mail.SubjectEncoding = Encoding.UTF8;
                //邮件正文
                mail.Body = model.Body;
                mail.BodyEncoding = Encoding.UTF8;
                //开始发送邮件
                smtpClient.Send(mail);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            
        }
    }

    public class SendMailFormModel
    {
        /// <summary>
        /// SMTP服务器名
        /// </summary>
        public string SmtpServer { get; set; }

        /// <summary>
        /// 发送人电子邮箱账号
        /// </summary>
        public string SenderEmailAddress { get; set; }

        /// <summary>
        /// 发送人电子邮箱密码
        /// </summary>
        public string SenderEmailPassword { get; set; }

        /// <summary>
        /// 接收人，多个接收人用英文逗号分隔
        /// </summary>
        public string Recipients { get; set; }

        /// <summary>
        /// 邮件主题
        /// </summary>
        public string Subject { get; set; }

        /// <summary>
        /// 邮件正文
        /// </summary>
        public string Body { get; set; }
    }
}